<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head th:replace="fragments/head :: commonHead('项目成员管理')">
    <!-- 页面特定样式将由head.html中的通用头部替代 -->
</head>
<body class="bg-light">
    <div class="container py-5">
        <div class="row mb-4">
            <div class="col">
                <div class="d-flex justify-content-between align-items-center flex-wrap">
                    <div>
                        <h2 class="fw-bold text-primary mb-2">项目成员管理</h2>
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb mb-0">
                                <li class="breadcrumb-item"><a th:href="@{/}" class="text-decoration-none">首页</a></li>
                                <li class="breadcrumb-item"><a th:href="@{/project/list}" class="text-decoration-none">项目列表</a></li>
                                <li class="breadcrumb-item"><a th:href="@{/project/{id}(id=${project.id})}" class="text-decoration-none">项目详情</a></li>
                                <li class="breadcrumb-item active" aria-current="page">项目成员</li>
                            </ol>
                        </nav>
                    </div>
                    <div class="mt-3 mt-md-0">
                        <a th:href="@{/}" class="btn btn-outline-primary">
                            <i class="fas fa-home me-1"></i> 返回首页
                        </a>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card border-0 shadow-sm rounded-3 overflow-hidden">
            <div class="card-header bg-white d-flex justify-content-between align-items-center py-3">
                <h5 class="mb-0 text-primary">
                    <i class="fas fa-users me-2"></i>项目: <span th:text="${project.name}"></span>
                </h5>
                <div sec:authorize="hasAnyRole('ADMIN', 'MANAGER')">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                        <i class="fas fa-plus me-1"></i> 添加成员
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th class="ps-4">成员ID</th>
                                <th>用户名</th>
                                <th>真实姓名</th>
                                <th>角色</th>
                                <th>加入时间</th>
                                <th sec:authorize="hasAnyRole('ADMIN', 'MANAGER')" class="text-center">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr th:if="${members.empty}">
                                <td colspan="6" class="text-center py-4">暂无项目成员</td>
                            </tr>
                            <tr th:each="member, stat : ${members}">
                                <td class="ps-4" th:text="${member.id}"></td>
                                <td th:text="${member.username}"></td>
                                <td th:text="${member.realName}"></td>
                                <td>
                                    <span th:with="relation=${memberRelations[stat.index]}" 
                                          th:class="${relation.role == 1 ? 'badge bg-danger' : (relation.role == 2 ? 'badge bg-warning' : 'badge bg-success')}"
                                          th:text="${relation.role == 1 ? '项目经理' : (relation.role == 2 ? '风险管理员' : '普通成员')}">
                                    </span>
                                </td>
                                <td th:with="relation=${memberRelations[stat.index]}" 
                                    th:text="${#dates.format(relation.joinTime, 'yyyy-MM-dd HH:mm:ss')}"></td>
                                <td sec:authorize="hasAnyRole('ADMIN', 'MANAGER')" class="text-center">
                                    <div class="btn-group btn-group-sm">
                                        <button type="button" class="btn btn-info text-white"
                                                th:data-project-id="${project.id}"
                                                th:data-user-id="${member.id}"
                                                th:data-username="${member.username}"
                                                th:data-role="${memberRelations[stat.index].role}"
                                                onclick="showChangeRoleModal(this.getAttribute('data-project-id'), this.getAttribute('data-user-id'), this.getAttribute('data-username'), this.getAttribute('data-role'))">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-danger" 
                                                th:data-project-id="${project.id}"
                                                th:data-user-id="${member.id}"
                                                th:data-username="${member.username}"
                                                onclick="confirmDeleteMember(this.getAttribute('data-project-id'), this.getAttribute('data-user-id'), this.getAttribute('data-username'))">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 添加成员模态框 -->
    <div class="modal fade" id="addMemberModal" tabindex="-1" aria-labelledby="addMemberModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addMemberModalLabel">添加项目成员</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addMemberForm">
                        <div class="mb-3">
                            <label for="userSelect" class="form-label">选择用户</label>
                            <select class="form-select" id="userSelect" name="userId" required>
                                <option value="">-- 请选择用户 --</option>
                                <option th:each="user : ${allUsers}" 
                                        th:value="${user.id}" 
                                        th:text="${user.username} + ' (' + ${user.realName} + ')'"></option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="roleSelect" class="form-label">选择角色</label>
                            <select class="form-select" id="roleSelect" name="role" required>
                                <option value="3">普通成员</option>
                                <option value="2">风险管理员</option>
                                <option value="1">项目经理</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addMember()">添加</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 修改角色模态框 -->
    <div class="modal fade" id="changeRoleModal" tabindex="-1" aria-labelledby="changeRoleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="changeRoleModalLabel">修改成员角色</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>修改 <span id="changeMemberUsername"></span> 的角色:</p>
                    <form id="changeRoleForm">
                        <input type="hidden" id="changeProjectId" name="projectId">
                        <input type="hidden" id="changeUserId" name="userId">
                        <div class="mb-3">
                            <select class="form-select" id="changeRoleSelect" name="role" required>
                                <option value="3">普通成员</option>
                                <option value="2">风险管理员</option>
                                <option value="1">项目经理</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="changeRole()">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>确定要从项目中删除成员 <span id="deleteMemberUsername"></span> 吗？</p>
                    <input type="hidden" id="deleteProjectId">
                    <input type="hidden" id="deleteUserId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="deleteMember()">删除</button>
                </div>
            </div>
        </div>
    </div>
    
    <footer class="footer mt-auto py-4 bg-dark text-white">
        <div class="container text-center">
            <span>© 2025 项目风险管理系统 | 版本 1.0</span>
        </div>
    </footer>
    
    <script th:inline="javascript">
        // 添加成员
        function addMember() {
            const userId = document.getElementById('userSelect').value;
            const role = document.getElementById('roleSelect').value;
            const projectId = /*[[${project.id}]]*/ '1'; // 使用安全的注释形式来包含Thymeleaf表达式
            
            if (!userId) {
                alert('请选择用户');
                return;
            }
            
            console.log('添加单个成员 - 用户ID:', userId);
            
            // 使用FormData构建表单数据
            const formData = new FormData();
            formData.append('projectId', projectId);
            formData.append('userId', userId);
            formData.append('role', role);
            
            console.log('添加成员表单数据:');
            for (let pair of formData.entries()) {
                console.log(pair[0] + ': ' + pair[1]);
            }
            
            // 获取CSRF令牌
            const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
            const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
            
            fetch('/risk-management/project-member/add', {
                method: 'POST',
                headers: {
                    [csrfHeader]: csrfToken
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            })
            .then(result => {
                if (result.code === 200) {
                    alert('添加成员成功');
                    location.reload();
                } else {
                    alert('添加成员失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('添加成员失败:', error);
                alert('添加成员请求失败，请稍后重试');
            });
        }
        
        // 显示修改角色模态框
        function showChangeRoleModal(projectId, userId, username, currentRole) {
            document.getElementById('changeProjectId').value = projectId;
            document.getElementById('changeUserId').value = userId;
            document.getElementById('changeMemberUsername').textContent = username;
            document.getElementById('changeRoleSelect').value = currentRole;
            
            const changeRoleModal = new bootstrap.Modal(document.getElementById('changeRoleModal'));
            changeRoleModal.show();
        }
        
        // 修改角色
        function changeRole() {
            const projectId = document.getElementById('changeProjectId').value;
            const userId = document.getElementById('changeUserId').value;
            const role = document.getElementById('changeRoleSelect').value;
            
            // 使用FormData构建表单数据
            const formData = new FormData();
            formData.append('projectId', projectId);
            formData.append('userId', userId);
            formData.append('role', role);
            
            // 获取CSRF令牌
            const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
            const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
            
            fetch('/risk-management/project-member/update-role', {
                method: 'POST',
                headers: {
                    [csrfHeader]: csrfToken
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            })
            .then(result => {
                if (result.code === 200) {
                    alert('修改角色成功');
                    location.reload();
                } else {
                    alert('修改角色失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('修改角色失败:', error);
                alert('修改角色请求失败，请稍后重试');
            });
        }
        
        // 确认删除成员
        function confirmDeleteMember(projectId, userId, username) {
            document.getElementById('deleteProjectId').value = projectId;
            document.getElementById('deleteUserId').value = userId;
            document.getElementById('deleteMemberUsername').textContent = username;
            
            const deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
            deleteModal.show();
        }
        
        // 删除成员
        function deleteMember() {
            const projectId = document.getElementById('deleteProjectId').value;
            const userId = document.getElementById('deleteUserId').value;
            
            // 使用FormData构建表单数据
            const formData = new FormData();
            formData.append('projectId', projectId);
            formData.append('userId', userId);
            
            // 获取CSRF令牌
            const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
            const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
            
            fetch('/risk-management/project-member/delete', {
                method: 'POST',
                headers: {
                    [csrfHeader]: csrfToken
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            })
            .then(result => {
                if (result.code === 200) {
                    alert('删除成员成功');
                    location.reload();
                } else {
                    alert('删除成员失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('删除成员失败:', error);
                alert('删除成员请求失败，请稍后重试');
            });
        }
        
        // 初始化Bootstrap组件
        document.addEventListener('DOMContentLoaded', function() {
            // 获取所有模态框元素
            const modals = document.querySelectorAll('.modal');
            
            // 将它们初始化为Bootstrap模态框
            modals.forEach(modalEl => {
                new bootstrap.Modal(modalEl);
            });
        });
    </script>
</body>
</html> 